import axios from 'axios'
const service = axios.create({
  baseURL: import.meta.env.PROD
    ? import.meta.env.VITE_APP_BACKEND_ORIGIN + import.meta.env.VITE_APP_PREFIX_API
    : import.meta.env.VITE_APP_PREFIX_API
})
/**请求拦截器 */
service.interceptors.request.use((config) => {
  return config
})

/**响应拦截器 */
service.interceptors.response.use(
  ({ data }) => data,
  (error) => {
    return Promise.reject(error)
  }
)

export const $GET = (url, data, config) => request('GET', url, data, config)

export const $POST = (url, data, config) => request('POST', url, data, config)

export const $DELETE = (url, data, config) => request('DELETE', url, data, config)

const request = (method, url, data, config = {}) => {
  let requestData = {}

  /**表单类型请求 */
  if (
    config.headers &&
    (config?.headers['Content-Type'] || '') == 'application/x-www-form-urlencoded;charset=UTF-8'
  ) {
    requestData = new FormData()
    Object.entries(data).forEach(([key, value]) => requestData.append(key, value))
  } else {
    /**JSON类型请求 */
    requestData = data
  }
  const option = { method, url }
  method == 'GET' ? (option.params = requestData) : (option.data = requestData)

  return service({ ...option, ...config })
}

/**请求全局注册 */
export const ApiRejister = (app) => {
  Object.entries({ $GET, $POST, $DELETE }).forEach(
    ([key, global]) => (app.config.globalProperties[key] = global)
  )
}

export default service
